<template>
  <div class="box asset-quality-box">
    <!-- 标题 -->
    <div class="tit" data-icon="growth">
      <div class="tit-content">
        <span class="tit-main">资产质量与风险暴露</span>
        <transition name="group-name-fade" mode="out-in">
          <span 
            :key="currentGroupIndex" 
            class="group-name" 
            @click="manualSwitchToNextGroup"
          >{{ currentGroupName }}</span>
        </transition>
      </div>
      <div class="bottom-line"></div>
    </div>

    <!-- 轮播内容区域 -->
    <div class="boxnav" style="padding: 10px; overflow: hidden;">
      <div class="asset-quality-container">
        <transition name="group-fade" mode="out-in">
          <div :key="currentGroupIndex" class="content-group">
            
            <!-- 第一组：变化趋势 -->
            <div v-if="currentGroupIndex === 0" class="trend-dashboard">
              <div class="metrics-list-vertical">
                
                <div class="metric-item-vertical npl-metric">
                  <div class="metric-status-bar npl-bar"></div>
                  <div class="metric-info-vertical">
                    <div class="metric-title-vertical">不良贷款率</div>
                    <div class="metric-balance">{{ currentValues.nplBalance }}</div>
                  </div>
                  <div class="metric-values-vertical">
                    <div class="main-value-vertical">{{ currentValues.npl }}</div>
                    <div class="change-indicator" :class="currentValues.nplChange.startsWith('+') ? 'increase' : 'decrease'">
                      {{ currentValues.nplChange }}
                      <span class="change-type">{{ changeTypes.npl }}</span>
                    </div>
                  </div>
                </div>

                <div class="metric-item-vertical attention-metric">
                  <div class="metric-status-bar attention-bar"></div>
                  <div class="metric-info-vertical">
                    <div class="metric-title-vertical">关注类贷款占比</div>
                    <div class="metric-balance">{{ currentValues.attentionBalance }}</div>
                  </div>
                  <div class="metric-values-vertical">
                    <div class="main-value-vertical">{{ currentValues.attention }}</div>
                    <div class="change-indicator" :class="currentValues.attentionChange.startsWith('+') ? 'increase' : 'decrease'">
                      {{ currentValues.attentionChange }}
                      <span class="change-type">{{ changeTypes.attention }}</span>
                    </div>
                  </div>
                </div>

                <div class="metric-item-vertical provision-metric">
                  <div class="metric-status-bar provision-bar"></div>
                  <div class="metric-info-vertical">
                    <div class="metric-title-vertical">拨备覆盖率</div>
                   
                  </div>
                  <div class="metric-values-vertical">
                    <div class="main-value-vertical">{{ currentValues.provision }}</div>
                    <div class="change-indicator" :class="currentValues.provisionChange.startsWith('+') ? 'increase' : 'decrease'">
                      {{ currentValues.provisionChange }}
                      <span class="change-type">{{ changeTypes.provision }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 混合图表容器 -->
              <div class="trend-chart-container-vertical">
                <div class="trend-chart-wrapper">
                  <div ref="trendChart" class="trend-chart-el"></div>
                </div>
                <div class="chart-legend">
                  <div class="legend-item">
                    <div class="legend-color bar-npl"></div>
                    <span>不良贷款率（左轴）</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color bar-attention"></div>
                    <span>关注类贷款占比（左轴）</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color line-provision"></div>
                    <span>拨备覆盖率（右轴）</span>
                  </div>
                </div>
              </div>
            </div>

          
<div v-if="currentGroupIndex === 1" class="structure-analyzer" ref="structureGroup">
              <div class="four-dimension-charts">
                <div class="dimension-section">
                  <div class="dimension-title">按业务条线</div>
                  <div class="pie-chart" ref="businessLineChart"></div>
                </div>
                
                <div class="dimension-section">
                  <div class="dimension-title">按行业投向</div>
                  <div class="pie-chart" ref="industryChart"></div>
                </div>
                
                <div class="dimension-section">
                  <div class="dimension-title">按担保方式</div>
                  <div class="pie-chart" ref="guaranteeChart"></div>
                </div>
                
                <div class="dimension-section">
                  <div class="dimension-title">按企业规模</div>
                  <div class="pie-chart" ref="scaleChart"></div>
                </div>
              </div>
            </div>

           
            <div v-if="currentGroupIndex === 2" class="risk-detector">
              <div class="detector-cards">
                <div class="detector-card critical">
                  <div class="detector-header">
                    <span class="detector-name">逾期90天/不良贷款比</span>
                    <span class="detector-subtitle">测谎仪</span>
                  </div>
                  <div class="detector-value">
                    <span class="big-value">85%</span>
                    <span class="status-badge danger">红色警报</span>
                  </div>
                  <div class="detector-baseline">监管要求: ≈100%</div>
                  <div class="detector-alert">严重预警：不良分类不真实！</div>
                </div>

                <div class="detector-card warning">
                  <div class="detector-header">
                    <span class="detector-name">关注类贷款迁徙率</span>
                    <span class="detector-subtitle">加速器</span>
                  </div>
                  <div class="detector-value">
                    <span class="big-value">15%</span>
                    <span class="status-badge warning">橙色</span>
                  </div>
                  <div class="detector-baseline">上季度: 12%</div>
                  <div class="detector-alert">恶化速度加快！</div>
                </div>
              </div>
            </div>

          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useIndicatorAPI } from '../composables/useIndicatorAPI.js'

const { getIndicatorData } = useIndicatorAPI()

// 三组数据配置
const assetQualityGroups = [
  {
    groupName: '变化趋势',
    key: 'trend'
  },
  {
    groupName: '结构分析', 
    key: 'structure'
  },
  {
    groupName: '潜在风险',
    key: 'detector'
  }
]

// 轮播相关状态
const currentGroupIndex = ref(0)
const currentGroupName = ref(assetQualityGroups[0].groupName)
const isTransitioning = ref(false)
let carouselTimer = null

// Chart refs
const structureGroup = ref(null)
const businessLineChart = ref(null)
const industryChart = ref(null)
const guaranteeChart = ref(null)
const scaleChart = ref(null)
const trendChart = ref(null)

let chartInstances = []
let trendChartInstance = null

// 趋势图相关状态
const activeMetric = ref('npl')

// 真实趋势数据（从API获取）
const trendData = ref({
  npl: {
    label: '不良贷款率',
    data: [],
    borderColor: '#FF6B6B',
    backgroundColor: 'rgba(255, 107, 107, 0.1)'
  },
  attention: {
    label: '关注类贷款占比',
    data: [],
    borderColor: '#FFA726',
    backgroundColor: 'rgba(255, 167, 38, 0.1)'
  },
  provision: {
    label: '贷款拨备率',
    data: [],
    borderColor: '#29D9D5',
    backgroundColor: 'rgba(41, 217, 213, 0.1)'
  }
})

// 当前指标值（显示在卡片上）
const currentValues = ref({
  npl: '0.00%',
  nplChange: '+0.00%',
  nplBalance: '0.00亿元',
  attention: '0.00%', 
  attentionChange: '+0.00%',
  attentionBalance: '0.00亿元',
  provision: '0%',
  provisionChange: '+0.0%'
})

// 变化类型配置（环比/同比）
const changeTypes = ref({
  npl: '同比',
  attention: '同比', 
  provision: '同比'
})

// X轴标签：优先使用接口返回的月末日期，显示为“YYYY年M月”
const monthLabels = ref([])
const formatMonthLabel = (bussDt) => {
  if (!bussDt || typeof bussDt !== 'string') return ''
  const y = bussDt.slice(0, 4)
  const m = String(parseInt(bussDt.slice(5, 7), 10))
  return `${y}年${m}月`
}

// 兜底：最近12个月月末，显示为“YYYY年M月”
const generateMonthLabels = () => {
  const labels = []
  const now = new Date()
  for (let i = 11; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i + 1, 0) // 当月最后一天
    const y = d.getFullYear()
    const m = d.getMonth() + 1
    labels.push(`${y}年${m}月`)
  }
  return labels
}


// 监听容器尺寸自动 resize
const setupAutoResize = (chart, container) => {
  try {
    if (typeof ResizeObserver !== 'undefined') {
      const ro = new ResizeObserver(() => {
        chart.resize()
      })
      ro.observe(container)
    } else {
      window.addEventListener('resize', () => chart.resize())
      setTimeout(() => chart.resize(), 100)
    }
  } catch (e) {}
}

// 获取不同维度的饼图样式配置
const getPieChartConfig = (title, data) => {
  let config = {
    radius: '70%',
    borderRadius: 3,
    borderWidth: 1,
    shadowBlur: 8,
    shadowOffsetX: 2,
    shadowOffsetY: 2
  }
  
  switch (title) {
    case '按业务条线':
      config = {
        ...config,
        radius: ['30%', '75%'], // 环形图
        borderRadius: 12,
        borderWidth: 2,
        shadowBlur: 12,
        shadowColor: 'rgba(255, 107, 107, 0.4)'
      }
      break
    case '按行业投向':
      config = {
        ...config,
        radius: '78%', // 标准饼图
        borderRadius: 8,
        borderWidth: 2,
        shadowBlur: 10,
        shadowColor: 'rgba(41, 217, 213, 0.4)'
      }
      break
    case '按担保方式':
      config = {
        ...config,
        radius: ['20%', '70%'], // 中等环形图
        borderRadius: 15,
        borderWidth: 3,
        shadowBlur: 15,
        shadowColor: 'rgba(233, 30, 99, 0.4)'
      }
      break
    case '按企业规模':
      config = {
        ...config,
        radius: '72%', // 玫瑰图效果
        borderRadius: 10,
        borderWidth: 2,
        shadowBlur: 12,
        shadowColor: 'rgba(156, 39, 176, 0.4)',
        roseType: 'area' // 玫瑰图
      }
      break
  }
  
  return config
}

// 初始化饼图
const initPieChart = (container, data, title) => {
  if (!container) {
    console.warn('饼图容器不存在:', title)
    return null
  }
  
  try {
    const chart = echarts.init(container)
    chartInstances.push(chart)
    
    const styleConfig = getPieChartConfig(title, data)
    
    const option = {
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(0,0,0,0.9)',
        borderColor: 'rgba(255,255,255,0.2)',
        borderWidth: 1,
        textStyle: { 
          color: '#fff',
          fontSize: 12
        },
        formatter: '{b}: {c}% ({d}%)',
        extraCssText: 'border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.4);'
      },
      legend: {
        show: false
      },
      series: [{
        type: 'pie',
        radius: styleConfig.radius,
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        roseType: styleConfig.roseType,
        itemStyle: {
          borderRadius: styleConfig.borderRadius,
          borderColor: '#fff',
          borderWidth: styleConfig.borderWidth,
          shadowBlur: styleConfig.shadowBlur,
          shadowOffsetX: styleConfig.shadowOffsetX,
          shadowOffsetY: styleConfig.shadowOffsetY,
          shadowColor: styleConfig.shadowColor
        },
        label: {
          show: true,
          position: title === '按业务条线' || title === '按担保方式' ? 'inside' : 'outside',
          fontSize: 11,
          fontWeight: 'bold',
          color: '#fff',
          formatter: '{d}%',
          textShadowBlur: 2,
          textShadowColor: 'rgba(0,0,0,0.8)'
        },
        labelLine: {
          show: title === '按行业投向' || title === '按企业规模',
          length: 8,
          length2: 5,
          lineStyle: {
            color: '#fff',
            width: 1
          }
        },
        emphasis: {
          scale: true,
          scaleSize: 5,
          label: {
            show: true,
            fontSize: 13,
            fontWeight: 'bold',
            color: '#fff',
            textShadowBlur: 3,
            textShadowColor: 'rgba(0,0,0,0.8)'
          },
          itemStyle: {
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowColor: 'rgba(255, 255, 255, 0.3)'
          }
        },
        animationType: 'expansion',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        },
        data: data.map((item, index) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: getEnhancedColorByRisk(item.risk || 'normal', title, index)
          }
        }))
      }]
    }
    
    chart.setOption(option)
    // 确保初次渲染后根据容器尺寸调整
    setupAutoResize(chart, container)
    setTimeout(() => chart.resize(), 50)
    console.log('饼图初始化成功:', title, data)
    return chart
  } catch (error) {
    console.error('饼图初始化失败:', title, error)
    return null
  }
}

// 根据风险等级获取颜色
const getColorByRisk = (risk) => {
  switch (risk) {
    case 'high': return '#FF6B6B'
    case 'warning': return '#FFA726'
    case 'normal': return '#4ECDC4'
    default: return '#29D9D5'
  }
}

// 获取增强版颜色配置（根据维度和索引）
const getEnhancedColorByRisk = (risk, title, index) => {
  const colorPalettes = {
    '按业务条线': [
      '#FF6B6B', // 鲜红色 - 对公
      '#4ECDC4'  // 青绿色 - 零售
    ],
    '按行业投向': [
      '#FF5722', // 深橙红色 - 制造业
      '#00BCD4', // 青蓝色 - 房地产
      '#FF9800', // 橙色 - 批发零售
      '#4CAF50'  // 绿色 - 其他
    ],
    '按担保方式': [
      '#E91E63', // 粉红色 - 抵质押
      '#FFC107', // 金黄色 - 信用
      '#00ACC1'  // 青色 - 保证
    ],
    '按企业规模': [
      '#9C27B0', // 紫色 - 大型
      '#00E676', // 亮绿色 - 小微
      '#78909C'  // 蓝灰色 - 中型
    ]
  }
  
  const colors = colorPalettes[title] || ['#29D9D5', '#FF6B6B', '#FFA726', '#4CAF50']
  return colors[index % colors.length]
}

// 切换到下一组
const switchToNextGroup = async () => {
  if (isTransitioning.value) return
  
  isTransitioning.value = true
  
  // 切换到下一组
  currentGroupIndex.value = (currentGroupIndex.value + 1) % assetQualityGroups.length
  currentGroupName.value = assetQualityGroups[currentGroupIndex.value].groupName
  
  // 等待DOM更新后初始化图表
  await nextTick()
  initChartsForCurrentGroup()
  
  // 延迟重置转换状态
  setTimeout(() => {
    isTransitioning.value = false
  }, 600)
}

// 等待第二组 DOM refs 可用
const waitForStructureRefs = async (maxWaitMs = 2000) => {
  const start = Date.now()
  while (Date.now() - start < maxWaitMs) {
    await nextTick()
    if (businessLineChart.value && industryChart.value && guaranteeChart.value && scaleChart.value) {
      return true
    }
    await new Promise(r => setTimeout(r, 50))
  }
  return false
}

// 加载资产质量数据
const loadAssetQualityData = async () => {
  try {
    console.debug('[BusinessGrowth] 开始加载资产质量数据...')
    
    // 定义指标名称映射（参考其他组件的命名）
    const indicatorNames = {
      npl: '不良贷款率',
      attention: '关注类贷款占比', 
      provision: '拨备覆盖率',  // 修改为拨备覆盖率，这是更常用的指标名
      nplBalance: '不良贷款余额',
      attentionBalance: '关注类贷款余额'
    }
    
    // 并行获取五个指标的数据，使用Promise.allSettled处理部分失败
    const [nplResult, attentionResult, provisionResult, nplBalanceResult, attentionBalanceResult] = await Promise.allSettled([
      getIndicatorData(indicatorNames.npl),
      getIndicatorData(indicatorNames.attention),
      // 拨备覆盖率按来源限定到"信用风险指标补录表"
      getIndicatorData({ name: indicatorNames.provision, where: "ori='信用风险指标补录表'" }),
      // 不良贷款余额
      getIndicatorData(indicatorNames.nplBalance),
      // 关注类贷款余额
      getIndicatorData(indicatorNames.attentionBalance)
    ])
    
    // 处理不良贷款率数据
    if (nplResult.status === 'fulfilled' && nplResult.value) {
      console.log('不良贷款率API响应:', nplResult.value)
      const nplData = nplResult.value.datas || nplResult.value.data
      if (nplData && nplData.length > 0) {
        console.log('不良贷款率数据结构:', nplData[0])
        
        // 按时间排序，取最近12个月
        const sortedData = nplData.sort((a, b) => new Date(b[0]) - new Date(a[0]))
        const recentData = sortedData.slice(0, 12).reverse() // 反转为时间正序
        // 基于数据的月末日期生成中文标签
        monthLabels.value = recentData.map(item => formatMonthLabel(item[0]))
        
        // 提取数值并转换（参考KeyIndicators的处理方式）
        const values = recentData.map(item => {
          let value = parseFloat(item[3] || item.index_vl || item.index_value || 0)
          // 不良贷款率需要乘以100转换为百分比显示
          if (value < 1) {
            value = value * 100
          }
          return value
        })
        
        // 更新趋势数据
        trendData.value.npl.data = values
        
        // 计算当前值和同比变化
        if (values.length >= 12) {
          const currentValue = values[values.length - 1]  // 最新月份
          const yearAgoValue = values[values.length - 12] // 12个月前同期
          const change = currentValue - yearAgoValue
          
          console.log('不良贷款率同比计算:', {
            当前值: currentValue,
            去年同期值: yearAgoValue,
            同比变化: change,
            数据长度: values.length
          })
          
          currentValues.value.npl = `${currentValue.toFixed(2)}%`
          currentValues.value.nplChange = `${change >= 0 ? '+' : ''}${change.toFixed(2)}%`
        } else if (values.length >= 2) {
          // 数据不足12个月时，使用环比作为备选
          const currentValue = values[values.length - 1]
          const previousValue = values[values.length - 2]
          const change = currentValue - previousValue
          
          currentValues.value.npl = `${currentValue.toFixed(2)}%`
          currentValues.value.nplChange = `${change >= 0 ? '+' : ''}${change.toFixed(2)}%`
        } else if (values.length >= 1) {
          currentValues.value.npl = `${values[0].toFixed(2)}%`
        }
      }
    } else {
      console.warn('不良贷款率获取失败:', nplResult.reason)
    }
    
    // 处理关注类贷款占比数据
    if (attentionResult.status === 'fulfilled' && attentionResult.value) {
      console.log('关注类贷款占比API响应:', attentionResult.value)
      const attentionData = attentionResult.value.datas || attentionResult.value.data
      if (attentionData && attentionData.length > 0) {
        console.log('关注类贷款占比数据结构:', attentionData[0])
        
        const sortedData = attentionData.sort((a, b) => new Date(b[0]) - new Date(a[0]))
        const recentData = sortedData.slice(0, 12).reverse()
        if (monthLabels.value.length === 0) {
          monthLabels.value = recentData.map(item => formatMonthLabel(item[0]))
        }
        
        const values = recentData.map(item => {
          let value = parseFloat(item[3] || item.index_vl || item.index_value || 0)
          // 关注类贷款占比需要乘以100转换为百分比显示
          if (value < 1) {
            value = value * 100
          }
          return value
        })
        
        trendData.value.attention.data = values
        
        // 计算关注类贷款占比的同比变化
        if (values.length >= 12) {
          const currentValue = values[values.length - 1]  // 最新月份
          const yearAgoValue = values[values.length - 12] // 12个月前同期
          const change = currentValue - yearAgoValue
          
          currentValues.value.attention = `${currentValue.toFixed(2)}%`
          currentValues.value.attentionChange = `${change >= 0 ? '+' : ''}${change.toFixed(2)}%`
        } else if (values.length >= 2) {
          // 数据不足12个月时，使用环比作为备选
          const currentValue = values[values.length - 1]
          const previousValue = values[values.length - 2]
          const change = currentValue - previousValue
          
          currentValues.value.attention = `${currentValue.toFixed(2)}%`
          currentValues.value.attentionChange = `${change >= 0 ? '+' : ''}${change.toFixed(2)}%`
        } else if (values.length >= 1) {
          currentValues.value.attention = `${values[0].toFixed(2)}%`
        }
      }
    } else {
      console.warn('关注类贷款占比获取失败:', attentionResult.reason)
    }
    
    // 处理拨备覆盖率数据
    if (provisionResult.status === 'fulfilled' && provisionResult.value) {
      console.log('拨备覆盖率API响应:', provisionResult.value)
      const provisionData = provisionResult.value.datas || provisionResult.value.data
      if (provisionData && provisionData.length > 0) {
        console.log('拨备覆盖率数据结构:', provisionData[0])
        
        const sortedData = provisionData.sort((a, b) => new Date(b[0]) - new Date(a[0]))
        const recentData = sortedData.slice(0, 12).reverse()
        if (monthLabels.value.length === 0) {
          monthLabels.value = recentData.map(item => formatMonthLabel(item[0]))
        }
        
        const values = recentData.map(item => {
          let value = parseFloat(item[3] || item.index_vl || item.index_value || 0)
          // 拨备覆盖率需要乘以100转换为百分比显示
          if (value < 10) {
            value = value * 100
          }
          return value
        })
        
        trendData.value.provision.data = values
        
        // 计算拨备覆盖率的同比变化
        if (values.length >= 12) {
          const currentValue = values[values.length - 1]  // 最新月份
          const yearAgoValue = values[values.length - 12] // 12个月前同期
          const change = currentValue - yearAgoValue
          
          currentValues.value.provision = `${currentValue.toFixed(0)}%`
          currentValues.value.provisionChange = `${change >= 0 ? '+' : ''}${change.toFixed(1)}%`
        } else if (values.length >= 2) {
          // 数据不足12个月时，使用环比作为备选
          const currentValue = values[values.length - 1]
          const previousValue = values[values.length - 2]
          const change = currentValue - previousValue
          
          currentValues.value.provision = `${currentValue.toFixed(0)}%`
          currentValues.value.provisionChange = `${change >= 0 ? '+' : ''}${change.toFixed(1)}%`
        } else if (values.length >= 1) {
          currentValues.value.provision = `${values[0].toFixed(0)}%`
        }
      }
    } else {
      console.warn('拨备覆盖率获取失败:', provisionResult.reason)
    }
    
    // 处理不良贷款余额数据
    if (nplBalanceResult.status === 'fulfilled' && nplBalanceResult.value) {
      console.log('不良贷款余额API响应:', nplBalanceResult.value)
      const nplBalanceData = nplBalanceResult.value.datas || nplBalanceResult.value.data
      if (nplBalanceData && nplBalanceData.length > 0) {
        console.log('不良贷款余额数据结构:', nplBalanceData[0])
        
        // 获取最新的余额数据（第一条记录，因为按时间倒序）
        const latestBalance = parseFloat(nplBalanceData[0][3] || nplBalanceData[0].index_vl || nplBalanceData[0].index_value || 0)
        
        // 转换为亿元显示
        const balanceInYi = latestBalance / 100000000
        currentValues.value.nplBalance = `${balanceInYi.toFixed(2)}亿元`
      }
    } else {
      console.warn('不良贷款余额获取失败:', nplBalanceResult.reason)
    }
    
    // 处理关注类贷款余额数据
    if (attentionBalanceResult.status === 'fulfilled' && attentionBalanceResult.value) {
      console.log('关注类贷款余额API响应:', attentionBalanceResult.value)
      const attentionBalanceData = attentionBalanceResult.value.datas || attentionBalanceResult.value.data
      if (attentionBalanceData && attentionBalanceData.length > 0) {
        console.log('关注类贷款余额数据结构:', attentionBalanceData[0])
        
        // 获取最新的余额数据（第一条记录，因为按时间倒序）
        const latestBalance = parseFloat(attentionBalanceData[0][3] || attentionBalanceData[0].index_vl || attentionBalanceData[0].index_value || 0)
        
        // 转换为亿元显示
        const balanceInYi = latestBalance / 100000000
        currentValues.value.attentionBalance = `${balanceInYi.toFixed(2)}亿元`
      }
    } else {
      console.warn('关注类贷款余额获取失败:', attentionBalanceResult.reason)
    }
    
    console.log('资产质量数据加载完成')
    console.log('当前值:', currentValues.value)
    console.log('趋势数据:', trendData.value)
    
    // 重新初始化图表
    if (currentGroupIndex.value === 0) {
      setTimeout(() => {
        initTrendChart()
      }, 100)
    }
    
  } catch (error) {
    console.error('加载资产质量数据失败:', error)
    
    // 使用默认数据（参考其他组件的降级处理）
    trendData.value = {
      npl: {
        label: '不良贷款率',
        data: [1.72, 1.74, 1.73, 1.75, 1.78, 1.80, 1.79, 1.81, 1.82, 1.83, 1.80, 1.85],
        borderColor: '#FF6B6B',
        backgroundColor: 'rgba(255, 107, 107, 0.1)'
      },
      attention: {
        label: '关注类贷款占比',
        data: [2.95, 3.05, 3.10, 3.15, 3.20, 3.25, 3.30, 3.35, 3.40, 3.45, 3.25, 3.50],
        borderColor: '#FFA726',
        backgroundColor: 'rgba(255, 167, 38, 0.1)'
      },
      provision: {
        label: '贷款拨备率',
        data: [180.5, 178.2, 175.1, 172.4, 170.1, 168.5, 165.3, 163.1, 161.0, 159.5, 161.0, 155.2],
        borderColor: '#29D9D5',
        backgroundColor: 'rgba(41, 217, 213, 0.1)'
      }
    }
    
    currentValues.value = {
      npl: '1.85%',
      nplChange: '+0.05%',
      nplBalance: '125.68亿元',
      attention: '3.50%',
      attentionChange: '+0.25%',
      attentionBalance: '89.42亿元',
      provision: '155%',
      provisionChange: '-5.0%'
    }
  }
}

// 选择指标函数
const selectMetric = (metricKey) => {
  activeMetric.value = metricKey
  updateTrendChart(metricKey)
}

// 初始化混合图表（柱状图+折线图）
const initTrendChart = () => {
  if (!trendChart.value) return
  
  try {
    const labels = monthLabels.value.length ? monthLabels.value : generateMonthLabels()
    
    if (trendChartInstance) {
      try { trendChartInstance.dispose() } catch (e) {}
      trendChartInstance = null
    }
    trendChartInstance = echarts.init(
      trendChart.value,
      null,
      {
        renderer: 'canvas',
        devicePixelRatio: Math.max(1, window.devicePixelRatio || 1)
      }
    )
    
    // 动态计算左右轴范围
    const leftValues = [...(trendData.value.npl.data || []), ...(trendData.value.attention.data || [])].filter(v => typeof v === 'number' && !isNaN(v))
    const leftMinRaw = leftValues.length ? Math.min(...leftValues) : 0
    const leftMaxRaw = leftValues.length ? Math.max(...leftValues) : 4
    const leftPadding = Math.max(0.05, (leftMaxRaw - leftMinRaw) * 0.1)
    const leftMin = Math.max(0, parseFloat((leftMinRaw - leftPadding).toFixed(2)))
    const leftMax = parseFloat((leftMaxRaw + leftPadding).toFixed(2))

    const rightValues = (trendData.value.provision.data || []).filter(v => typeof v === 'number' && !isNaN(v))
    const rightMinRaw = rightValues.length ? Math.min(...rightValues) : 150
    const rightMaxRaw = rightValues.length ? Math.max(...rightValues) : 185
    const rightPadding = Math.max(1, (rightMaxRaw - rightMinRaw) * 0.08)
    const rightMin = Math.floor(rightMinRaw - rightPadding)
    const rightMax = Math.ceil(rightMaxRaw + rightPadding)

    const option = {
      // 背景和整体样式
      backgroundColor: 'transparent',

      // 优化的提示框 - 扁平风格
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(15, 23, 42, 0.96)',
        borderColor: 'rgba(59, 130, 246, 0.6)',
        borderWidth: 1,
        textStyle: { 
          color: '#f1f5f9',
          fontSize: 12,
          fontWeight: '500'
        },
        formatter: function(params) {
          let result = `<div style="font-weight: 600; margin-bottom: 8px; color: #60a5fa; font-size: 13px;">${params[0].name}</div>`
          params.forEach(param => {
            const color = param.color
            const icon = param.seriesName === '拨备覆盖率' ? '●' : '■'
            result += `<div style="margin: 4px 0; display: flex; align-items: center;">
              <span style="color:${color}; margin-right: 10px; font-size: 14px;">${icon}</span>
              <span style="flex: 1;">${param.seriesName}</span>
              <span style="font-weight: 600; margin-left: 15px; font-size: 13px;">${param.value}%</span>
            </div>`
          })
          return result
        },
        extraCssText: `
          border-radius: 8px; 
          box-shadow: 0 4px 20px rgba(0,0,0,0.3);
          backdrop-filter: blur(6px);
          padding: 16px;
        `
      },
      
      // 图例 - 扁平风格，放到图表上方
      legend: {
        data: [
          { name: '不良贷款率', icon: 'rect' },
          { name: '关注类贷款占比', icon: 'rect' },
          { name: '拨备覆盖率', icon: 'circle' }
        ],
        textStyle: {
          color: '#cbd5e1',
          fontSize: 11,
          fontWeight: '500'
        },
        top: 8,
        right: 12,
        orient: 'horizontal',
        itemWidth: 14,
        itemHeight: 8,
        itemGap: 15,
        backgroundColor: 'transparent',
        padding: [6, 12],
        borderRadius: 6
      },
      
      // 网格布局 - 扁平风格，扩大图表区域
      grid: {
        left: '0%',
        right: '0%',
        bottom: '0%',
        top: '15%',
        containLabel: true
      },
      
      // X轴 - 扁平风格
      xAxis: {
        type: 'category',
        data: labels,
        axisLine: {
          lineStyle: { 
            color: 'rgba(148, 163, 184, 0.4)',
            width: 2
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#94a3b8',
          fontSize: 10,
          fontWeight: '500',
          rotate: 0,
          margin: 12,
          formatter: function(value) {
            return value;
          }
        },
        splitLine: {
          show: false
        }
      },
      
      // 双Y轴 - 扁平风格
      yAxis: [
        {
          type: 'value',
          name: '',
          nameTextStyle: {
            color: '#f97316',
            fontSize: 11,
            fontWeight: '600',
            padding: [0, 0, 0, -10]
          },
          position: 'left',
          axisLine: {
            show: true,
            lineStyle: { 
              color: 'rgba(249, 115, 22, 0.5)',
              width: 2
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#f97316',
            fontSize: 9,
            fontWeight: '600',
            formatter: '{value}%'
          },
          splitLine: {
            lineStyle: { 
              color: 'rgba(148, 163, 184, 0.15)',
              type: 'dashed'
            }
          },
          min: leftMin,
          max: leftMax
        },
        {
          type: 'value',
          name: '',
          nameTextStyle: {
            color: '#06b6d4',
            fontSize: 11,
            fontWeight: '600',
            padding: [0, -10, 0, 0]
          },
          position: 'right',
          axisLine: {
            show: true,
            lineStyle: { 
              color: 'rgba(6, 182, 212, 0.5)',
              width: 2
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#06b6d4',
            fontSize: 9,
            fontWeight: '600',
            formatter: '{value}%'
          },
          splitLine: {
            show: false
          },
          min: rightMin,
          max: rightMax
        }
      ],
      
      // 系列设计 - 扁平风格，柱子更宽
      series: [
        {
          name: '不良贷款率',
          type: 'bar',
          yAxisIndex: 0,
          data: trendData.value.npl.data,
          barWidth: '28%',
          itemStyle: {
            color: '#ef4444',
            borderRadius: [4, 4, 0, 0],
            shadowBlur: 4,
            shadowColor: 'rgba(239, 68, 68, 0.2)',
            shadowOffsetY: 1
          },
          emphasis: {
            itemStyle: {
              color: '#dc2626',
              shadowBlur: 6,
              shadowColor: 'rgba(239, 68, 68, 0.3)'
            }
          }
        },
        {
          name: '关注类贷款占比',
          type: 'bar',
          yAxisIndex: 0,
          data: trendData.value.attention.data,
          barWidth: '28%',
          itemStyle: {
            color: '#f97316',
            borderRadius: [4, 4, 0, 0],
            shadowBlur: 4,
            shadowColor: 'rgba(249, 115, 22, 0.2)',
            shadowOffsetY: 1
          },
          emphasis: {
            itemStyle: {
              color: '#ea580c',
              shadowBlur: 6,
              shadowColor: 'rgba(249, 115, 22, 0.3)'
            }
          }
        },
        {
          name: '拨备覆盖率',
          type: 'line',
          yAxisIndex: 1,
          data: trendData.value.provision.data,
          z: 5,
          zlevel: 1,
          smooth: true,
          smoothMonotone: 'x',
          lineStyle: {
            color: '#06b6d4',
            width: 4,
            shadowBlur: 2,
            shadowColor: 'rgba(6, 182, 212, 0.2)',
            shadowOffsetY: 1
          },
          itemStyle: {
            color: '#06b6d4',
            borderWidth: 3,
            borderColor: '#ffffff',
            shadowBlur: 2,
            shadowColor: 'rgba(6, 182, 212, 0.3)'
          },
          symbol: 'circle',
          symbolSize: 8,
          emphasis: {
            itemStyle: {
              shadowBlur: 6,
              shadowColor: 'rgba(6, 182, 212, 0.4)',
              borderWidth: 4
            },
            lineStyle: {
              width: 6,
              shadowBlur: 4
            }
          }
        }
      ],
      
      // 扁平风格动画
      animation: true,
      animationDuration: 800,
      animationEasing: 'cubicInOut',
      animationDelayUpdate: function (idx) {
        return idx * 30;
      }
    }
    
    trendChartInstance.setOption(option)
    // 自适应并避免缩放模糊
    setupAutoResize(trendChartInstance, trendChart.value)
    setTimeout(() => trendChartInstance && trendChartInstance.resize(), 50)
    console.log('混合图表初始化成功')
  } catch (error) {
    console.error('混合图表初始化失败:', error)
  }
}

// 更新趋势图（现在是混合图表，不需要单独更新）
const updateTrendChart = (metricKey) => {
  // 混合图表显示所有三个指标，不需要根据选择的指标单独更新
  // 保留此函数以维持兼容性，但实际上混合图表会同时显示所有数据
  console.log(`选择了指标: ${metricKey}，混合图表显示所有指标数据`)
}

// 为当前组初始化图表
const initChartsForCurrentGroup = async () => {
  // 清理现有图表
  chartInstances.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
  chartInstances = []
  
  // 根据当前组初始化对应的图表
  if (currentGroupIndex.value === 0) {
    // 第一组：初始化趋势图
    setTimeout(() => {
      initTrendChart()
    }, 500)
  } else if (currentGroupIndex.value === 1) {
    // 第二组：四个维度的饼图
    const ready = await waitForStructureRefs()
    console.log('结构分析 refs 是否就绪:', ready, {
      businessLineChart: businessLineChart.value,
      industryChart: industryChart.value,
      guaranteeChart: guaranteeChart.value,
      scaleChart: scaleChart.value
    })
    if (!ready) {
      console.warn('等待图表容器超时，尝试强制初始化')
    }
    
    // 维度一：按业务条线
    initPieChart(businessLineChart.value, [
      { name: '对公', value: 65, risk: 'high' },
      { name: '零售', value: 35, risk: 'normal' }
    ], '按业务条线')
    
    // 维度二：按行业投向
    initPieChart(industryChart.value, [
      { name: '制造业', value: 40, risk: 'high' },
      { name: '房地产', value: 30, risk: 'normal' },
      { name: '批发零售', value: 20, risk: 'normal' },
      { name: '其他', value: 10, risk: 'normal' }
    ], '按行业投向')
    
    // 维度三：按担保方式
    initPieChart(guaranteeChart.value, [
      { name: '抵质押', value: 40, risk: 'high' },
      { name: '信用', value: 35, risk: 'warning' },
      { name: '保证', value: 25, risk: 'normal' }
    ], '按担保方式')
    
    // 维度四：按企业规模
    initPieChart(scaleChart.value, [
      { name: '大型', value: 50, risk: 'high' },
      { name: '小微', value: 30, risk: 'normal' },
      { name: '中型', value: 20, risk: 'normal' }
    ], '按企业规模')
    
    // 统一调整
    setTimeout(() => {
      chartInstances.forEach(c => c && c.resize && c.resize())
    }, 100)
    }
  // 第一组和第三组不需要图表初始化
}

// 手动切换到下一组（仅通过按钮触发）
const manualSwitchToNextGroup = () => {
  switchToNextGroup()
}

// 停止轮播（保留函数以防需要）
const stopCarousel = () => {
  if (carouselTimer) {
    clearInterval(carouselTimer)
    carouselTimer = null
  }
}

onMounted(() => {
  // 先加载数据，然后初始化图表
  loadAssetQualityData().then(() => {
    setTimeout(() => {
      console.log('组件挂载，当前组索引:', currentGroupIndex.value)
      initChartsForCurrentGroup()
    }, 500)
  })
})

onUnmounted(() => {
  stopCarousel()
  chartInstances.forEach(chart => {
    if (chart) {
      chart.dispose()
    }
  })
  chartInstances = []
})
</script>

<style scoped>
.asset-quality-container {
  height: 100%;
  position: relative;
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
  display: flex;
  flex-direction: column;
}

.tit-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.tit-main {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}

.bottom-line {
  flex: 1;
  height: 2px;
  background: linear-gradient(to right, #00D4FF, transparent);
  margin-left: 10px;
}

/* 组名样式 - 透明风格统一，可点击 */
.group-name {
  font-size: 12px;
  color: white;
  font-weight: 500;
  background: rgba(255, 107, 107, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
  border: 1px solid rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
  white-space: nowrap;
  cursor: pointer;
  user-select: none;
}

.group-name:hover {
  background: rgba(255, 107, 107, 0.2);
  border-color: rgba(255, 107, 107, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.group-name:active {
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(255, 107, 107, 0.2);
}

/* 组名切换动画 */
.group-name-fade-enter-active,
.group-name-fade-leave-active {
  transition: all 0.3s ease;
}

.group-name-fade-enter-from {
  opacity: 0;
  transform: translateX(10px) scale(0.9);
}

.group-name-fade-leave-to {
  opacity: 0;
  transform: translateX(-10px) scale(0.9);
}

/* 组切换动画效果 */
.group-fade-enter-active,
.group-fade-leave-active {
  transition: all 0.6s ease;
}

.group-fade-enter-from {
  opacity: 0;
}

.group-fade-leave-to {
  opacity: 0;
}

.content-group {
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 第一组：趋势仪表盘样式 */
.trend-dashboard {
  height: 100%;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  height: 100%;
}

.metric-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 15px 18px;
  border-left: 4px solid #FF6B6B;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 120px;
  transition: all 0.3s ease;
}

.metric-card:hover {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.08));
  border-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.metric-name {
  font-size: 14px;
  font-weight: bold;
  color: #fff;
}

.metric-type {
  font-size: 11px;
  color: #888;
  background: rgba(255, 255, 255, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
}

.metric-value {
  display: flex;
  align-items: baseline;
  gap: 10px;
  margin-bottom: 8px;
}

.value {
  font-size: 24px;
  font-weight: bold;
  color: #29d9d5;
}

.change {
  font-size: 12px;
  padding: 3px 8px;
  border-radius: 10px;
  font-weight: 500;
}

.change.increase {
  background: #FF6B6B;
  color: #fff;
}

.change.decrease {
  background: #FFA726;
  color: #fff;
}


.audit-note {
  font-size: 9px;
  padding: 2px 4px;
  border-radius: 3px;
  margin-top: 3px;
  line-height: 1.2;
}

.audit-note.danger {
  background: rgba(255, 107, 107, 0.2);
  border: 1px solid #FF6B6B;
  color: #FFB3B3;
}

.audit-note.warning {
  background: rgba(255, 167, 38, 0.2);
  border: 1px solid #FFA726;
  color: #FFD4A3;
}

/* 第二组：四维度结构分析样式 */
.structure-analyzer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.structure-title {
  font-size: 16px;
  color: #00D4FF;
  text-align: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.four-dimension-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 6px;
  height: 100%;
  flex: 1;
}

.dimension-section {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.dimension-title {
  font-size: 12px;
  color: #00D4FF;
  margin-bottom: 4px;
  text-align: center;
  font-weight: bold;
}

.pie-chart {
  width: 100%;
  height: 150px;
  flex: 1;
  min-height: 120px;
}

.dimension-summary {
  margin-top: 8px;
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.dimension-summary span {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 8px;
  font-weight: 500;
}

.dimension-summary .high-risk {
  color: #FF6B6B;
  background: rgba(255, 107, 107, 0.15);
  border: 1px solid rgba(255, 107, 107, 0.3);
}

.dimension-summary .warning {
  color: #FFA726;
  background: rgba(255, 167, 38, 0.15);
  border: 1px solid rgba(255, 167, 38, 0.3);
}

.dimension-summary .normal {
  color: #4ECDC4;
  background: rgba(78, 205, 196, 0.15);
  border: 1px solid rgba(78, 205, 196, 0.3);
}

/* 第三组：潜在风险挖掘机样式 */
.risk-detector {
  height: 100%;
}

.detector-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  height: 100%;
}

.detector-card {
  background: rgba(255, 255, 255, 0.08);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.detector-card.critical {
  border: 2px solid #FF6B6B;
  background: rgba(255, 107, 107, 0.1);
}

.detector-card.warning {
  border: 2px solid #FFA726;
  background: rgba(255, 167, 38, 0.1);
}

.detector-header {
  margin-bottom: 12px;
}

.detector-name {
  display: block;
  font-size: 14px;
  font-weight: bold;
  color: #fff;
  line-height: 1.2;
  margin-bottom: 4px;
}

.detector-subtitle {
  font-size: 11px;
  color: #888;
}

.detector-value {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.big-value {
  font-size: 32px;
  font-weight: bold;
  color: #00D4FF;
}

.status-badge {
  font-size: 10px;
  padding: 3px 8px;
  border-radius: 10px;
  font-weight: 500;
}

.status-badge.danger {
  background: #FF6B6B;
  color: #fff;
}

.status-badge.warning {
  background: #FFA726;
  color: #fff;
}

.detector-baseline {
  font-size: 11px;
  color: #888;
  margin-bottom: 6px;
}

.detector-alert {
  font-size: 12px;
  font-weight: bold;
  color: #FFB3B3;
  line-height: 1.3;
}

/* 资产质量组件特殊样式 - 与地图组件对齐 */
.asset-quality-box {
  margin-bottom: 0 !important;
  /* 与中间地图盒子底部对齐（地图 boxnav 高度为 550px） */
  height: 550px !important;
  display: flex;
  flex-direction: column;
}

.asset-quality-box .tit {
  flex-shrink: 0;
}

.asset-quality-box .boxnav {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: auto !important;
}

/* 响应式调整：项目仅面向大屏，已移除小屏媒体查询 */

/* 垂直布局样式 */
.metrics-list-vertical {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 0 0 auto;
}

.metric-item-vertical {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 6px 10px;
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 44px;
}

.metric-item-vertical:hover {
  border-color: rgba(255, 255, 255, 0.4);
  background: rgba(255, 255, 255, 0.08);
}

.metric-item-vertical.active {
  border-color: #00BFFF;
  box-shadow: 0 0 15px rgba(0, 191, 255, 0.3);
  background: rgba(0, 191, 255, 0.1);
}

.metric-status-bar {
  position: absolute;
  left: -1px;
  top: 20%;
  height: 60%;
  width: 4px;
  border-radius: 0 2px 2px 0;
}

.npl-bar {
  background: #FF6B6B;
  box-shadow: 0 0 8px #FF6B6B;
}

.attention-bar {
  background: #FFA726;
  box-shadow: 0 0 8px #FFA726;
}

.provision-bar {
  background: #29D9D5;
  box-shadow: 0 0 8px #29D9D5;
}

.metric-info-vertical {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 15px;
}

.metric-title-vertical {
  font-size: 13px;
  color: #fff;
  font-weight: 500;
  margin-bottom: 2px;
  line-height: 1.2;
}

.metric-balance {
  font-size: 10px;
  color: #94a3b8;
  font-weight: 400;
  margin-top: 1px;
  opacity: 0.8;
  line-height: 1.1;
}

.metric-tag {
  font-size: 9px;
  padding: 1px 5px;
  border-radius: 4px;
  width: fit-content;
}

.npl-tag {
  background: rgba(255, 107, 107, 0.2);
  color: #FF6B6B;
}

.attention-tag {
  background: rgba(255, 167, 38, 0.2);
  color: #FFA726;
}

.provision-tag {
  background: rgba(41, 217, 213, 0.2);
  color: #29D9D5;
}

.metric-values-vertical {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  justify-content: center;
}

.main-value-vertical {
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
  line-height: 1;
}

.change-indicator {
  font-size: 11px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 4px;
}

.change-indicator.increase {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
}

.change-indicator.decrease {
  background: rgba(255, 167, 38, 0.2);
  color: #ffa726;
}

.change-type {
  font-size: 10px;
  opacity: 0.8;
  margin-left: 2px;
  font-weight: 400;
}

/* 趋势图容器 */
.trend-chart-container-vertical {
  flex: 1;
  min-height: 160px;
  margin-top: 1px;
}

.trend-chart-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

.trend-chart-canvas {
  width: 100% !important;
  height: 100% !important;
}

/* 新的 ECharts 容器元素，需占满父容器尺寸 */
.trend-chart-el {
  width: 100% !important;
  height: 100% !important;
}

/* 更新第一组样式 */
.trend-dashboard {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 指标摘要卡片 */
.metric-summary-card {
  background: rgba(0, 191, 255, 0.1);
  border: 1px solid rgba(0, 191, 255, 0.3);
  border-radius: 8px;
  padding: 6px 10px;
  margin-bottom: 6px;
}

.summary-title {
  font-size: 13px;
  font-weight: bold;
  color: #00BFFF;
  margin-bottom: 4px;
}

.summary-description {
  font-size: 10px;
  color: #A9C1E5;
  line-height: 1.3;
}

/* 图表标题 */
.chart-title {
  font-size: 12px;
  font-weight: bold;
  color: #fff;
  text-align: center;
  margin-bottom: 8px;
  padding: 4px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

/* 图表图例 */
.chart-legend {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 8px;
  padding: 6px 0;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 10px;
  color: #A9C1E5;
}

.legend-color {
  width: 12px;
  height: 8px;
  border-radius: 2px;
}

.bar-npl {
  background: linear-gradient(135deg, #FF6B6B, rgba(255, 107, 107, 0.6));
}

.bar-attention {
  background: linear-gradient(135deg, #FFA726, rgba(255, 167, 38, 0.6));
}

.line-provision {
  background: #29D9D5;
  border-radius: 50%;
  width: 8px;
  height: 8px;
}

/* 指标卡片样式优化 */
.metric-item-vertical.npl-metric {
  border-left-color: #FF6B6B;
}

.metric-item-vertical.attention-metric {
  border-left-color: #FFA726;
}

.metric-item-vertical.provision-metric {
  border-left-color: #29D9D5;
}
</style>
